﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;

namespace Meraz.Core.Commands
{
    public interface ISaveDomainsCommand : ICommand<List<Domain>> { }
    public class SaveDomainsCommand: BaseCommand, ISaveDomainsCommand
    {
        public List<Domain> Result { get; set; }
        public IDomainRepository Repository { get; set; }
        public SaveDomainsCommand(IDomainRepository repository)
        {
            Repository = repository ?? new DomainRepository();
        }

        public void Execute() {
            foreach (Domain domain in Result)
            {
                if (domain == null)
                    continue;
                Domain existing = null;
                if (domain.ID > 0)
                {
                    existing = Repository.GetById(domain.ID);
                    Transfer(existing, domain);
                    continue;
                }
                if (string.IsNullOrWhiteSpace(domain.Name))
                    throw new ApplicationException("Cannot save a Domain without an ID or Name");
                existing = Repository.Get(domain.Name);
                Transfer(existing, domain);
            }
            Commit();
        }
        void Transfer(Domain target, Domain source)
        {
            if (target == null)
                throw new ApplicationException("Failed to find Domain");
            target.IdeologyType = source.IdeologyType;
            target.MediaType = source.MediaType;
            target.OrganizationType = source.OrganizationType;
            target.PartyType = source.PartyType;
            target.SocialType = source.SocialType;
            target.ThemeType = source.ThemeType;
        }
    }
}
